package com.msgqer.rchat.client;

import java.util.Map;
import java.util.Objects;

import javax.websocket.Session;

import com.msgqer.rchat.event.CommunicationEvent;
import com.msgqer.rchat.message.MessageDto;

import cn.hutool.json.JSONUtil;

/**
 * 客户端信息
 * 
 * @author keaizhuzhu@公众号：面试怪圈 ;官网地址：{@link http://www.mianshiguaiquan.com}
 *         这里有更多面试、技术、学习资料及源码等
 *
 */
public class Client {
	/**
	 * 客户端Id
	 */
	private String clientId;
	/**
	 * 客户端名称
	 */
	private String clientName;
	/**
	 * 客户端头像
	 */
	private String clientHeader;

	/**
	 * 建立连接的session
	 */
	private Session session;

	public String getClientId() {
		return clientId;
	}

	public void setClientId(String clientId) {
		this.clientId = clientId;
	}

	public String getClientName() {
		return clientName;
	}

	public void setClientName(String clientName) {
		this.clientName = clientName;
	}

	public String getClientHeader() {
		return clientHeader;
	}

	public void setClientHeader(String clientHeader) {
		this.clientHeader = clientHeader;
	}

	public Session getSession() {
		return session;
	}

	public void setSession(Session session) {
		this.session = session;
	}

	/**
	 * 广播消息
	 * 
	 * @param message
	 * @param event
	 */
	public <T> void broadcast(CommunicationEvent<T> event) {

		// 获取所有的客户端
		Map<String, Client> clients = ClientManager.getConnectedClients();
		if (clients == null) {
			return;
		}

		// 广播消息
		for (Client client : clients.values()) {

			// 给某个客户端发送消息
			sendTo(client, event);
		}
	}

	/**
	 * 给某个客户端发送消息
	 * 
	 * @param client
	 * @param message
	 */
	public <T> void sendTo(Client toClient, CommunicationEvent<T> event) {
		if (toClient == null) {
			return;
		}

		// 获取会话
		Session session = toClient.getSession();
		
		// 设置发送给自己的消息标记
		if(event.getData() instanceof MessageDto) {
			((MessageDto)event.getData()).setIsYourself(Objects.equals(this.getClientId(), toClient.getClientId())?1:0);
		}

		// 如果连接是开启的，则发送
		if (session.isOpen()) {
			System.out.println("send to:" + toClient.getClientName() + ", event:" + event);

			// 发送给目标客户端
			synchronized (session) {
				try {
					
					session.getBasicRemote().sendText(JSONUtil.toJsonStr(event));
				} catch (Exception e) {
					
				}
			}
		}
	}

	@Override
	public String toString() {
		return "Client [clientId=" + clientId + ", clientName=" + clientName + ", clientHeader=" + clientHeader
				+ ", session=" + session + "]";
	}

}
